package net.lzzy.practicesapi1.web;

import net.lzzy.practicesapi1.constants.ApiConstant;
import net.lzzy.practicesapi1.constants.Messages;
import net.lzzy.practicesapi1.entities.User;
import net.lzzy.practicesapi1.services.UserService;
import net.lzzy.practicesapi1.utils.StringUtil;
import net.lzzy.practicesapi1.web.models.ApiResult;
import net.lzzy.practicesapi1.web.models.LoginInfo;
import net.lzzy.practicesapi1.web.models.VmUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping(ApiConstant.ROUTE_AUTH_ROOT)
public class AuthApiController {
    private final UserService service;
    @Autowired
    public AuthApiController(UserService service) {
        this.service = service;
    }
    /*
    * PothVariable处理URL模板参数（<a href="http://localhost/list?page=1&size=5">...</a>）
    * Request
    *  */
    @PostMapping(value=ApiConstant.ROUTE_AUTH_ROOT,produces =ApiConstant.API_PRODUCES )
  public ApiResult login(@RequestBody LoginInfo info){
        String userName=info.getUsername();
        String password=info.getPassword();
        String salt=service.getSalt(userName);
        User user=service.check(userName, StringUtil.md5Encode(password,salt));
        if (user==null){
            return new ApiResult(false, Messages.WRONG_PASSWORD.toString(), null);
        }if (user.getType()<0){
            return new ApiResult(false,Messages.SUCCESS.toString(), null);
        }
        VmUser vmUser=VmUser.apiLogin(user);
        return new ApiResult(true,Messages.SUCCESS.toString(), vmUser);
    }
    public ApiResult isUserExists(@PathVariable String user){
        boolean exists=service.isUserNameOccupied(user);
        return new ApiResult(true,exists?"用户已存在":"",exists);
    }
}
